package cn.wolfcode.trip.app.controller;


import cn.wolfcode.trip.app.utils.UploadUtil;
import cn.wolfcode.trip.app.utils.UserContext;
import cn.wolfcode.trip.base.domain.User;
import cn.wolfcode.trip.base.service.IUserService;
import cn.wolfcode.trip.base.utils.JSONResult;
import org.omg.PortableServer.ServantLocator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/images")
public class ImageController {
    @Autowired
    private IUserService userService;
    @Autowired
    private ServletContext ctx;

    /*
    * 头像的更新操作:
    * 请求资源:images
    * 请求方式:post--操作不是针对user,而是针对image
    * 请求参数:图片文件
    * 返回值:状态/图片路径
    * */
    @PostMapping
    @ResponseBody
    public Object updateImg(MultipartFile multipartFile){
        //为了兼容后面的操作,提前设计一个status的属性,如果传递的status=1,代表成功
        //注意:如果用domain无法封装的,可以用map
        Map<String,Object> map = new HashMap<String, Object>();
        try {
            //通过容器对象获取文件的相对路径(项目文件真实部署的路径)
            System.out.println(ctx.getRealPath("/upload"));
            /*F:/Java8/IdeaProjects/trip/app/src/main/webApp/upload*/
            //String imagePath = UploadUtil.upload(multipartFile, ctx.getRealPath("/upload"));
            String imagePath = UploadUtil.upload(multipartFile, UploadUtil.IMG_BASE_PATH+"/upload");
            map.put("url",imagePath);
            map.put("status",1);

        } catch (Exception e) {
            e.printStackTrace();
            map.put("url","");
            map.put("status",0);
        }
        return map;
    }

}
